//
//  QRCodeViewController.swift
//  WeiboSwift
//
//  Created by xiaokui wu on 9/11/16.
//  Copyright © 2016 wxk. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {

    @IBOutlet weak var containerView: UIView!
    // 底部工具条
    @IBOutlet weak var customTabBar: UITabBar!
    
    @IBOutlet weak var resultLabel: UILabel!
    // 冲击波顶部约束
    @IBOutlet weak var scanLineTopCons: NSLayoutConstraint!
    @IBOutlet weak var scanLineView: UIImageView!
    // 容器视图高度
    @IBOutlet weak var containerHeightCons: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 设置默认选中
        customTabBar.selectedItem = customTabBar.items?.first
        
        // 监听底部工具条的点击
        customTabBar.delegate = self
        
        // 开始扫描二维码
        scanQRCode()
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        startAnimation()
        
    }
    // MARK: - interal
    private func scanQRCode()
    {
        //1. 判断输入能否添加到会话中
        if !session.canAddInput(input) {
            return
        }
        //2. 判断输出能否添加到会话中
        if !session.canAddOutput(output) {
            return
        }
        //3. 添加输入输出到会话中
        session.addInput(input)
        session.addOutput(output)
        
        //4. 设置输出能够解析的数据类型
        output.metadataObjectTypes = output.availableMetadataObjectTypes// 一定要添加到会话后再设置
        
        //5. 设置监听输出解析到的数据
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
        //6. 添加预览图层
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        previewLayer.frame = view.bounds
        
        // 容器图层
        view.layer.addSublayer(containerLayer)
        containerLayer.frame = view.bounds
        //7. 开始扫描
        session.startRunning()
    
    }
    
    func startAnimation() {
        scanLineTopCons.constant = -containerHeightCons.constant
        view.layoutIfNeeded()//改变约束，需要调用下这个方法
        // 改约束，动画
        // 在闭包中，需要用self来访问属性
        UIView.animateWithDuration(2.0) {
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.scanLineTopCons.constant = self.containerHeightCons.constant
            self.view.layoutIfNeeded()
            
        }

    }
    // MARK: - event
    @IBAction func closeBtnClick(sender: AnyObject) {
        
        dismissViewControllerAnimated(true, completion: nil)
    }

    @IBAction func photoBtnClick(sender: AnyObject) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            Log("不能打开图片库")
            return
        }
        let imagePickerVc = UIImagePickerController()
        imagePickerVc.delegate = self
        presentViewController(imagePickerVc, animated: true, completion: nil)
    }
    
    // MARK: - lazy
    /// 输入对象
    private lazy var input: AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        return try? AVCaptureDeviceInput(device: device)
    }()
    /// 会话
    private lazy var session: AVCaptureSession = AVCaptureSession()
    
    /// 输出对象
    private lazy var output: AVCaptureMetadataOutput = {
        let out = AVCaptureMetadataOutput()
        // 比例范围
        // 默认是以横屏的左上角作为参照原点
        // out.rectOfInterest = CGRect(x: 0, y: 0, width: 1, height: 1)
        
        // 屏幕frame
        let rect = self.view.frame
        // containerView的frame
        let containerRect = self.containerView.frame
        
        let x = containerRect.origin.y / rect.height
        let y = containerRect.origin.x / rect.width
        let w = containerRect.height / rect.height
        let h = containerRect.width / rect.width
            
        out.rectOfInterest = CGRect(x: x, y: y, width: w, height: h)
        
        return out
    }()
    
    /// 预览图层
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
        return AVCaptureVideoPreviewLayer(session: self.session)
    }()
    
    // 专门保存描边的图层
    private lazy var containerLayer:CALayer = CALayer()
    
}

extension QRCodeViewController : UINavigationControllerDelegate, UIImagePickerControllerDelegate
{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        Log(info)
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else{
            return
        }
        // 从图片中读取二维码数据
        // 创建探测器
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyLow])
        // 探测数据
        let results = detector.featuresInImage(CIImage(image: image)!)
        // 读取数据
        for result in results
        {
            Log((result as! CIQRCodeFeature).messageString)
        }
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - AVCaptureMetadataOutputObjectsDelegate
extension QRCodeViewController : AVCaptureMetadataOutputObjectsDelegate
{
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!)
    {
        Log(metadataObjects.last?.stringValue)
        resultLabel.text = metadataObjects.last?.stringValue
        // 不管有没有数据，都先移除描边
        clearLayers()
        guard let metadata = metadataObjects.last as? AVMetadataObject else{
            return
        }
        // 转换四个角的坐标corner：
        let objc = previewLayer.transformedMetadataObjectForMetadataObject(metadata)
        Log(objc)
        // 描边
        drawLines(objc as! AVMetadataMachineReadableCodeObject)
    }
    
    // 绘制描边
    private func drawLines(objc: AVMetadataMachineReadableCodeObject) {
        
        guard let array = objc.corners else{
            return
        }
        // 创建图层，用于保存绘制的矩形
        let layer = CAShapeLayer()
        layer.lineWidth = 2
        layer.strokeColor = UIColor.greenColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        // 创建UIBezierPath，绘制矩形
        let path = UIBezierPath()
        
        var point = CGPointZero
        var index = 0
        CGPointMakeWithDictionaryRepresentation((array[index++] as! CFDictionary), &point)
        path.moveToPoint(point)
        
        while index < array.count {
            CGPointMakeWithDictionaryRepresentation((array[index++] as! CFDictionary), &point)
            path.addLineToPoint(point)
        }
        
        path.closePath()
        
        layer.path = path.CGPath
        
        // 把保存矩形的图层加到界面上
        containerLayer.addSublayer(layer)
    }
    
    // 移除描边
    private func clearLayers()
    {
        guard let subLayers = containerLayer.sublayers else{
            return
        }
        for layer in subLayers {
            layer.removeFromSuperlayer()
        }
    }
}

// MARK: - UITabBarDelegate
extension QRCodeViewController: UITabBarDelegate
{
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem)
    {
        containerHeightCons.constant = (item.tag == 1) ? 150 : 300
        view.layoutIfNeeded()
        
        // 移除动画
        scanLineView.layer.removeAllAnimations()
        
        // 重新开启
        startAnimation()
        
    }
}
